import JSEncrypt from 'jsencrypt';

const ENCRYPT_PUBLIC_KEY =
  'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCMgUtGOshZoIS31kzHQ3+JriFy7d3EVwCV4FmFN06RY/kUtFnJD/Gz8TQLZOKLLAqwVnj3DettFSAr+yni7DmSpg5ZpoKhYtAXCUQAY97QRh1J/rVVixsCgwrEy740CXObKPlnMMfEYnx+WCSVKaygZa3aKmFZGJQyE+By8GCuFQIDAQAB';

export function encryptPassword(password) {
  const encrypt = new JSEncrypt();
  encrypt.setPublicKey(ENCRYPT_PUBLIC_KEY);
  return encrypt.encrypt(password);
}

export function apimapCreator(apimapArr, UILessConfig) {
  // 在这里可以对请求做一些统一处理，如加前缀、加headers
  return apimapArr.map((option) =>
    Object.assign(option, {
      name: option.name || option.id,
      id: option.id,
      method: option.method || 'get',
      contentType: option.type || 'application/x-www-form-urlencoded',
      urls: {
        local: option.withHost ? option.url : `${UILessConfig.host}${option.url}`,
      },
      withCredentials: option.withCredentials,
    }));
}

export function requestFilter(config, UILessConfig) {
  if (config && config.headers) {
    config.headers['x-requested-with'] = 'XMLHttpRequest';
    config.headers.Authorization = `Bearer ${UILessConfig.accessToken}`;
    config.headers['X-Tenant-Id'] = `${UILessConfig.orgId}`;
    config.headers['X-Code-Timestamp'] = new Date().getTime();
    if (!config.env || config.env !== 'vpc') {
      config.headers['X-app-id'] = `${UILessConfig.appId}`;
    }
  }
  return config;
}

export const tools = {
  checkPasswordMinLength(password, minLength) {
    if (minLength < 0 || !minLength) {
      return true;
    }
    return password.length >= minLength;
  },
  checkPasswordMaxLength(password, maxLength) {
    if (maxLength < 0 || !maxLength) {
      return true;
    }
    return password.length <= maxLength;
  },
  checkMinLetters(password, minLetters) {
    if (minLetters < 0 || !minLetters) {
      return true;
    }

    let letterCount = 0;
    for (let i = 0; i < password.length; i++) {
      if (
        (password[i] >= 'a' && password[i] <= 'z') ||
        (password[i] >= 'A' && password[i] <= 'Z')
      ) {
        letterCount += 1;
        if (letterCount >= minLetters) {
          break;
        }
      }
    }

    return letterCount >= minLetters;
  },
  checkMinDigits(password, minDigits) {
    if (minDigits < 0 || !minDigits) {
      return true;
    }

    let numberCnt = 0;
    for (let i = 0; i < password.length; i++) {
      if (password[i] >= '0' && password[i] <= '9') {
        numberCnt += 1;
        if (numberCnt >= minDigits) {
          break;
        }
      }
    }

    return numberCnt >= minDigits;
  },
  checkMinSpecialCharacters(password, minSpecialCharacters) {
    if (minSpecialCharacters < 0 || !minSpecialCharacters) {
      return true;
    }

    let specialCnt = 0;
    for (let i = 0; i < password.length; i++) {
      if (this.checkContainSpecialCharaters(password[i])) {
        specialCnt += 1;
        if (specialCnt >= minSpecialCharacters) {
          break;
        }
      }
    }

    return specialCnt >= minSpecialCharacters;
  },
  checkContainSpecialCharaters(str) {
    const pattern = new RegExp(
      "[-+`~!@%#$^&*()=|{}':;',\\[\\].<>《》\\/?~！@#￥……&*（）——|{}【】‘；：”“'。，、？ \\\\]",
    );
    if (pattern.test(str)) {
      return true;
    }
    return false;
  },
  checkIsLegalCharaters(password) {
    const pattern = new RegExp(
      "^[-+A-Za-z0-9`~!@%#$^&*()=|{}':;',\\[\\].<>《》\\/?~！@#￥……&*（）——|{}【】‘；：”“'。，、？ \\\\]*$",
    );
    if (pattern.test(password)) {
      return true;
    }
    return false;
  },
};

function getCookie(name) {
  const value = `; ${document.cookie}`;
  const parts = value.split(`; ${name}=`);
  if (parts.length === 2) return parts.pop().split(';').shift();
}

function setCookie(name, value, dute, other = {}) {
  const exp = new Date();
  exp.setTime(exp.getTime() + parseInt(dute * 60 * 60, 10) * 1000);

  const config = {
    [name]: value,
    expires: exp.toUTCString(),
    ...other,
  };

  const cookie = Object.entries(config)
    .map(([k, v]) => `${k}=${v}`)
    .join('; ');
  document.cookie = cookie;
}

function isAliyunRamAccount() {
  const value = getCookie('login_aliyunid_pk');
  return !(value && value.length <= 16);
}

export default {
  apimapCreator,
  requestFilter,
  encryptPassword,
  getCookie,
  setCookie,
  isAliyunRamAccount,
  tools,
};
